﻿using Common.Communal;
using ERP.Domain.Scheduling;
using MediatR;
using Scheduling.Api.Read.Application.Command.CalendarCommand;
using SqlSugar;

namespace Scheduling.Api.Read.Application.CommandHandlers.CalendarHandler
{
    public class CalendarCreateCommandHandler : IRequestHandler<CalendarCreateCommand, ApiResult<List<Calendar>>>
    {
        public CalendarCreateCommandHandler(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }

        public ISqlSugarClient SqlSugar { get; }

        public Task<ApiResult<List<Calendar>>> Handle(CalendarCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<Calendar>> result = new ApiResult<List<Calendar>>();
            result.Code = EnumCode.Ok;
            result.Message = "日历显示成功";

            // 仅显示未删除记录
            var query = SqlSugar.Queryable<Calendar>()
                .Where(x => x.IsDelete == false);

            // 开始、结束日期
            if (request.StartDate.HasValue)
                query = query.Where(x => x.CalendarDate >= request.StartDate.Value);
            if (request.EndDate.HasValue)
                query = query.Where(x => x.CalendarDate <= request.EndDate.Value);

            // 是否工作日、是否加急
            if (request.IsWorkDay.HasValue)
                query = query.Where(x => x.IsWorkDay == request.IsWorkDay.Value);
            if (request.IsUrgentWorkday.HasValue)
                query = query.Where(x => x.IsUrgentWorkday == request.IsUrgentWorkday.Value);

            // 节假日类型
            if (!string.IsNullOrWhiteSpace(request.HoildayType))
                query = query.Where(x => x.HoildayType == request.HoildayType);

            // 加急原因关键字（模糊匹配）
            if (!string.IsNullOrWhiteSpace(request.ReasonKeyword))
                query = query.Where(x => x.UrgentReason.Contains(request.ReasonKeyword));

            var list = query.OrderBy(x => x.CalendarDate).ToList();

            result.Data = list;
            return Task.FromResult(result);
        }
    }
}
